// chat/chat.gateway.ts
import {
  WebSocketGateway,
  WebSocketServer,
  SubscribeMessage,
  MessageBody,
  ConnectedSocket,
  OnGatewayInit,
  OnGatewayConnection,
  OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway({ namespace: '/chat', cors: true })
export class ChatGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
  @WebSocketServer()
  server: Server;

  // 用户ID与socket.id映射
  private userMap = new Map<string, string>();

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  afterInit(server: Server) {
    console.log('WebSocket 网关已初始化');
  }
  handleConnection(client: Socket) {
    // console.log(`客户端连接: ${client.id}`);
    const userId = client.handshake.query?.userId as string;
    console.log(userId);
    if (userId) {
      // client.id = userId;
      this.userMap.set(userId, client.id);
    }
    // token鉴权 假设前端通过 query 传递 token
    // const token = client.handshake.query?.token as string;
    try {
      // console.log(token);
      // const payload = jwt.verify(token, 'your_jwt_secret'); // 替换为你的密钥
      // // 可将用户信息挂载到 client 对象
      // (client as any).user = payload;
      // console.log(`用户已鉴权: ${payload.username}`);
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (e: any) {
      console.log('WebSocket 鉴权失败，断开连接');
      client.disconnect();
    }
  }

  handleDisconnect(client: Socket) {
    console.log(`客户端断开: ${client.id}`);
    for (const [userId, socketId] of this.userMap.entries()) {
      if (socketId === client.id) {
        this.userMap.delete(userId);
        break;
      }
    }
  }

  @SubscribeMessage('privateMessage')
  handlePrivateMessage(
    @MessageBody() data: { toUserId: string; message: string },
    @ConnectedSocket() client: Socket,
  ) {
    const targetSocketId = this.userMap.get(data.toUserId);
    // console.log(targetSocketId);
    if (targetSocketId) {
      this.server.to(targetSocketId).emit('receivePrivateMessage', {
        from: client.id,
        message: data.message,
      });
    }
  }

  @SubscribeMessage('sendMessage')
  handleMessage(
    @MessageBody() data: { user: string; message: string },
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    @ConnectedSocket() client: Socket,
  ) {
    // 广播消息到所有客户端
    this.server.emit('receiveMessage', data);
  }

  // 群聊
  @SubscribeMessage('joinRoom')
  async handleJoinRoom(
    @MessageBody() data: { room: string },
    @ConnectedSocket() client: Socket,
  ) {
    await client.join(data.room);
    client.emit('joinedRoom', { room: data.room });
  }

  @SubscribeMessage('roomMessage')
  handleRoomMessage(
    @MessageBody() data: { room: string; message: string },
    @ConnectedSocket() client: Socket,
  ) {
    this.server.to(data.room).emit('receiveRoomMessage', {
      from: client.id,
      message: data.message,
      room: data.room,
    });
  }
  // 广播全局消息
  @SubscribeMessage('broadcast')
  handleBroadcast(@MessageBody() data: { message: string }) {
    this.server.emit('receiveBroadcast', {
      message: data.message,
    });
  }
}
